package com.oa.duban.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.mdp.core.entity.Tips;
import com.mdp.core.err.BizException;
import com.mdp.core.service.BaseService;
import com.mdp.safe.client.entity.User;
import com.mdp.safe.client.utils.LoginUtils;
import com.oa.duban.entity.*;
import com.oa.duban.mapper.DubanItemMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @author maimeng-mdp code-gen
 * @since 2023年10月8日
 */
@Service
public class DubanItemService extends BaseService<DubanItemMapper, DubanItem> {
    static Logger logger = LoggerFactory.getLogger(DubanItemService.class);

    /**
     * 自定义查询，支持多表关联
     *
     * @param page 分页条件
     * @param ew   一定要，并且必须加@Param("ew")注解
     * @param ext  如果xml中需要根据某些值进行特殊处理，可以通过这个进行传递，非必须，注解也可以不加
     * @return
     */
    public List<Map<String, Object>> selectListMapByWhere(IPage page, QueryWrapper ew, Map<String, Object> ext) {
        return baseMapper.selectListMapByWhere(page, ew, ext);
    }

    @Autowired
    DubanItemCoopDeptService dubanItemCoopDeptService;

    @Autowired
    DubanItemCoopUserService dubanItemCoopUserService;

    @Autowired
    DubanItemTaskService dubanItemTaskService;

    public static boolean useList(String[] arr, String targetValue) {
        if (arr != null) {
            return Arrays.asList(arr).contains(targetValue);
        }
        return false;
    }

    public List<Map<String, Object>> selectListMapByWhereAndTopQuery(IPage page, QueryWrapper qw, Map<String, Object> map) {
        //获取督办查询列表
//        List<Map<String, Object>> dubanList = baseMapper.selectListMapByWhereAndTopQuery(map);
        List<Map<String, Object>> dubanList = this.selectListMapByWhere(page, qw, map);

        if (!StringUtils.isEmpty(map.get("coopUsers"))) {
            if (dubanList != null && dubanList.size() > 0) {
                List<Map<String, Object>> dubanListRemove = new ArrayList<>();

                dubanList.forEach((duban) -> {
                    String id = (String) duban.get("id");

                    DubanItemCoopUser dubanItemCoopUser = new DubanItemCoopUser();
                    dubanItemCoopUser.setDubanItemId(id);
                    List<DubanItemCoopUser> dubanItemCoopUsers = dubanItemCoopUserService.selectListByWhere(dubanItemCoopUser);

                    if (dubanItemCoopUsers != null && dubanItemCoopUsers.size() > 0) {
                        List<DubanItemCoopUser> coopUsers = new ArrayList<>();
                        dubanItemCoopUsers.forEach((coopUser) -> {
                            if (useList((String[]) map.get("coopUsers"), coopUser.getUserId())) {
                                coopUsers.add(coopUser);
                            }
                        });
                        if (coopUsers.size() > 0) {
                            duban.put("coopUsers", dubanItemCoopUsers);
                        } else {
                            dubanListRemove.add(duban);
                        }
                    } else {
                        dubanListRemove.add(duban);
                    }
                });
                dubanList.removeAll(dubanListRemove);
            }
        } else {
            if (dubanList != null && dubanList.size() > 0) {

                dubanList.forEach((duban) -> {
                    String id = (String) duban.get("id");
                    DubanItemCoopUser dubanItemCoopUser = new DubanItemCoopUser();
                    dubanItemCoopUser.setDubanItemId(id);
                    List<DubanItemCoopUser> dubanItemCoopUsers = dubanItemCoopUserService.selectListByWhere(dubanItemCoopUser);
                    DubanItemCoopDept dubanItemCoopDept = new DubanItemCoopDept();
                    dubanItemCoopDept.setDubanItemId(id);
                    List<DubanItemCoopDept> dubanItemCoopDepts = dubanItemCoopDeptService.selectListByWhere(dubanItemCoopDept);
                    duban.put("coopDepts", dubanItemCoopDepts);
                    duban.put("coopUsers", dubanItemCoopUsers);
                });

            }
        }

        return dubanList;
    }

    /**
     * 请在此类添加自定义函数
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public Integer saveDuban(DubanItemVo dubanItemVo) {

        if (StringUtils.isEmpty(dubanItemVo.getStatus())) {
            dubanItemVo.setStatus("0");
        }

        if (StringUtils.isEmpty(dubanItemVo.getCreateTime())) {
            dubanItemVo.setCreateTime(new Date());
        }

        if (StringUtils.isEmpty(dubanItemVo.getProgress())) {
            dubanItemVo.setProgress("0");
        }
        if (StringUtils.isEmpty(dubanItemVo.getCreateUserid())) {
            User currentUserInfo = LoginUtils.getCurrentUserInfo();
            dubanItemVo.setCreateUserid(currentUserInfo.getUserid());
            dubanItemVo.setCreateUsername(currentUserInfo.getUsername());
        }

        DubanItem dubanItem = new DubanItem();
        BeanUtils.copyProperties(dubanItemVo, dubanItem); //拷贝属性值

        if (StringUtils.isEmpty(dubanItem.getId())) {
            dubanItem.setId(this.createKey("id"));
        } else {
            DubanItem dubanItemQuery = new DubanItem(dubanItem.getId());
            if (this.countByWhere(dubanItemQuery) > 0) {
                throw new BizException("督办事项字号重复，请修改后重试！");
            }
        }
        int insert = this.insert(dubanItem);
        saveOtherMessage(dubanItemVo, null, dubanItem);

        return insert;
    }

    public void saveOtherMessage(DubanItemVo dubanItemVo, Tips tips, DubanItem dubanItem) {
        //保存事项item的协办部门
        List<DubanItemCoopDept> coopDepts = dubanItemVo.getCoopDept();
        if (coopDepts != null && coopDepts.size() > 0) {
            coopDepts.forEach(dubanItemCoopDept -> {
                dubanItemCoopDept.setDubanItemId(dubanItem.getId());

                //判断dubanItemCoopDept的主键是否为空
                if (StringUtils.isEmpty(dubanItemCoopDept.getId())) {
                    dubanItemCoopDept.setId(dubanItemCoopDeptService.createKey("id"));
                } else {
                    DubanItemCoopDept dubanItemCoopDeptQuery = new DubanItemCoopDept(dubanItemCoopDept.getId());
                    if (dubanItemCoopDeptService.countByWhere(dubanItemCoopDeptQuery) > 0) {
                        throw new BizException("编号重复，请修改编号再提交！");
                    }
                }
                dubanItemCoopDeptService.insert(dubanItemCoopDept);
            });
        }

        //保存事项的协办用户
        List<DubanItemCoopUser> coopUsers = dubanItemVo.getCoopUser();
        if (coopUsers != null && coopUsers.size() > 0) {
            coopUsers.forEach((dubanItemCoopUser) -> {
                dubanItemCoopUser.setDubanItemId(dubanItem.getId());

                if (StringUtils.isEmpty(dubanItemCoopUser.getId())) {
                    dubanItemCoopUser.setId(dubanItemCoopUserService.createKey("id"));
                } else {
                    DubanItemCoopUser dubanItemCoopUserQuery = new DubanItemCoopUser(dubanItemCoopUser.getId());
                    if (dubanItemCoopUserService.countByWhere(dubanItemCoopUserQuery) > 0) {
                        throw new BizException("编号重复，请修改编号再提交！");
                    }
                }
                dubanItemCoopUserService.insert(dubanItemCoopUser);

            });
        }

        //保存任务
        List<DubanItemTaskVo> tasks = dubanItemVo.getTasks();
        if (tasks != null && tasks.size() > 0) {
            tasks.forEach((taskVo) -> {
                taskVo.setDubanId(dubanItem.getId());
                taskVo.setCategoryId(dubanItem.getCategoryId());
                taskVo.setCategoryName(dubanItem.getCategoryName());
                dubanItemTaskService.save(taskVo);
            });
        }
    }

    /**
     * 删除督办事项及全部信息
     *
     * @param dubanItem
     * @return
     */
    @Transactional(propagation = Propagation.REQUIRED)
    public Integer removeDuban(DubanItem dubanItem) {
        int pk = this.deleteByPk(dubanItem);
        deleteOtherMessage(dubanItem);
        return pk;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void deleteOtherMessage(DubanItem dubanItem) {
        DubanItemCoopDept dubanItemCoopDept = new DubanItemCoopDept();
        dubanItemCoopDept.setDubanItemId(dubanItem.getId());
        dubanItemCoopDeptService.deleteByWhere(dubanItemCoopDept);

        DubanItemCoopUser dubanItemCoopUser = new DubanItemCoopUser();
        dubanItemCoopUser.setDubanItemId(dubanItem.getId());
        dubanItemCoopUserService.deleteByWhere(dubanItemCoopUser);

        DubanItemTask dubanItemTask = new DubanItemTask();
        dubanItemTask.setDubanId(dubanItem.getId());
        List<DubanItemTask> dubanItemTasks = dubanItemTaskService.selectListByWhere(dubanItemTask);
        if (dubanItemTasks != null && dubanItemTasks.size() > 0) {
            dubanItemTasks.forEach((task) -> {
                dubanItemTaskService.removeDubanItemTask(task);
            });
        }
    }

    /**
     * 获取督办事项的信息
     *
     * @param dubanItem
     * @return
     */
    public DubanItemVo selectAllMessage(DubanItem dubanItem) {

        DubanItemVo dubanItemVo = new DubanItemVo();

        //查询督办事项
        DubanItem oneObject = this.selectOneObject(dubanItem);
        if (oneObject != null) {
            BeanUtils.copyProperties(oneObject, dubanItemVo);
        }

        //查询督办协办部门
        DubanItemCoopDept dubanItemCoopDept = new DubanItemCoopDept();
        dubanItemCoopDept.setDubanItemId(oneObject.getId());
        List<DubanItemCoopDept> dubanItemCoopDepts = dubanItemCoopDeptService.selectListByWhere(dubanItemCoopDept);
        dubanItemVo.setCoopDept(dubanItemCoopDepts);

        //查询督办协办
        DubanItemCoopUser dubanItemCoopUser = new DubanItemCoopUser();
        dubanItemCoopUser.setDubanItemId(oneObject.getId());
        List<DubanItemCoopUser> dubanItemTaskCoopUsers = dubanItemCoopUserService.selectListByWhere(dubanItemCoopUser);
        dubanItemVo.setCoopUser(dubanItemTaskCoopUsers);

        //查询督办任务
        DubanItemTask dubanItemTask = new DubanItemTask();
        dubanItemTask.setDubanId(oneObject.getId());
        List<DubanItemTask> dubanItemTasks = dubanItemTaskService.selectListByWhere(dubanItemTask);
        if (dubanItemTasks != null && dubanItemTasks.size() > 0) {
            List<DubanItemTaskVo> dubanItemTaskVos = new ArrayList<>();
            dubanItemTasks.forEach((task) -> {
                DubanItemTaskVo dubanItemTaskVo = new DubanItemTaskVo();
                BeanUtils.copyProperties(task, dubanItemTaskVo);
                DubanItemTaskVo itemTaskVo = dubanItemTaskService.getMessage(task, dubanItemTaskVo);
                dubanItemTaskVos.add(itemTaskVo);
            });
            dubanItemVo.setTasks(dubanItemTaskVos);
        }
        return dubanItemVo;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public Integer editDubanItem(DubanItemVo dubanItemVo) {

        Tips tips = new Tips();

        DubanItem dubanItem = new DubanItem();
        Integer update = null;

        if (StringUtils.isEmpty(dubanItemVo)) {
            throw new BizException("请求参数错误！");
        }
        BeanUtils.copyProperties(dubanItemVo, dubanItem);
        update = this.updateByPk(dubanItem);

        //其他 信息先删除，再添加
        deleteOtherMessage(dubanItem);
        //保存其他表的信息
        saveOtherMessage(dubanItemVo, tips, dubanItem);

        return update;
    }

    public void editMessage(DubanItemVo dubanItemVo) {
        //更新协办部门
        List<DubanItemCoopDept> coopDepts = dubanItemVo.getCoopDept();
        if (coopDepts != null && coopDepts.size() > 0) {
            for (DubanItemCoopDept coopDept : coopDepts) {
                dubanItemCoopDeptService.updateByPk(coopDept);
            }
        }

        //更新协办
        List<DubanItemCoopUser> coopUsers = dubanItemVo.getCoopUser();
        if (coopUsers != null && coopUsers.size() > 0) {
            for (DubanItemCoopUser coopUser : coopUsers) {
                dubanItemCoopUserService.updateByPk(coopUser);
            }
        }

        //更新任务
        List<DubanItemTaskVo> tasks = dubanItemVo.getTasks();
        if (tasks != null && tasks.size() > 0) {
            for (DubanItemTaskVo task : tasks) {
                Integer i = dubanItemTaskService.editTask(task);
            }
        }
    }
}

